package com.tiantianbook.mvpretrofitrxjavademo.model;

import com.tiantianbook.mvpretrofitrxjavademo.bean.Result;
import com.tiantianbook.mvpretrofitrxjavademo.http.DemoService;
import com.tiantianbook.mvpretrofitrxjavademo.view.main.MvpView;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * name:MvpModel
 * author:moo.
 * date:2016/8/31.
 * instruction:
 */
public class MvpModel {
    public void getData(final MvpView mvpView) {
        if (mvpView != null) {
            mvpView.beforeRequest();
        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(DemoService.ROOT_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        DemoService demoService = retrofit.create(DemoService.class);
        Observable<Result> result = demoService.getResult("ip", "www.baidu.com", DemoService.APP_KEY);
        result.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result>() {
                    @Override
                    public void onCompleted() {
                        //test
                        //你好
                        //test222
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Result result) {
                        if (result == null) {
                            if (mvpView != null) {
                                mvpView.afterRequest(null);
                            }
                        } else {
                            if (mvpView != null) {
                                String resultString = result.toString();
                                mvpView.afterRequest(resultString);
                            }
                        }
                    }
                });
    }

}
